package com.ycl.javacore.exam.limittest;

public class CheckCalledTimesInPeriod {

    private int limitTime;
    private long startMills;

    private int limitCount;

    // record the times that be called
    private static int count = 0;

    public CheckCalledTimesInPeriod(int mills, long startMills, int limitCount) {
        this.limitTime = mills;
        this.startMills = startMills;
        this.limitCount = limitCount;
    }

    /**
     * 这里的synchronized锁住count++，主要是要保证count++的原子性
     * 跟 private static AtomicInteger reqTimes = new AtomicInteger(0);不加synchronized一样
     */
    public synchronized void execute() {

        long nowMills = System.currentTimeMillis();

        count++;

        if (nowMills <= (startMills + limitTime * 1000) && count <= limitCount) {
            System.out.println(" Hello...The method is being called. ");
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        long startMills = System.currentTimeMillis();

        CheckCalledTimesInPeriod called = new CheckCalledTimesInPeriod(1, startMills, 60);

        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    called.execute();
                }
            }).start();
        }
    }
}